# -*- coding: utf-8 -*-

import datetime
from haystack import indexes

from django.conf import settings

from news.models import NewsDetail

class NewsDetailIndex(indexes.SearchIndex, indexes.Indexable):
    
    text = indexes.CharField(document=True, use_template=True)
    category = indexes.CharField(model_attr='category')
    url = indexes.CharField(model_attr='url', indexed=False)
    published_time = indexes.DateTimeField(model_attr='published_time', stored=False)
    keywords = indexes.MultiValueField(model_attr='keywords', stored=False)
    related_stocks = indexes.MultiValueField(null=True)

    def get_model(self):
        return NewsDetail

    def index_queryset(self, using=None):
        return self.get_model().objects.filter(date__lte=datetime.date.today(), add_succeeded=True)

    # for indexing
    def prepare_keywords(self, obj):
        return obj.keywords.split(settings.NEWS_KEYWORDS_DELIMITER)

    def prepare_related_stocks(self, obj):
        related_stock_list = []
        for stock in obj.related_stocks.all():
            related_stock_list.append(stock.code)
            related_stock_list.append(stock.short_name)
        return related_stock_list

